import 'dart:math';

import 'package:flutter/material.dart';

/// Extension on the [Color]
extension JMColorExtension on Color {
  /// JMColorExtension: Hex value string of the color.
  ///
  /// Example:
  /// ```dart
  /// Color.red.hexString
  /// ```
  String get hexString {
    String hexStr = value.toRadixString(16);
    return '#${hexStr.substring(2)}';
  }

  /// JMColorExtension: Hex color from a string to a color object.
  ///
  /// Example:
  /// ```dart
  /// Color.fromHexString('#ff0000')
  /// ```
  static Color fromHexString(String? val, {double alpha = 1.0, Color defVal = Colors.white}) {
    if (val == null || val.isEmpty) return defVal;

    val = val.toUpperCase();
    val = val.replaceAll("#", '');
    val = val.replaceAll("0x", '');
    final result = int.tryParse(val, radix: 16);
    if (result == null) return defVal;

    return Color(result).withOpacity(alpha);
  }

  /// JMColorExtension: Create random color.
  ///
  /// Example:
  /// ```dart
  /// Color.random
  /// ```
  static Color get random {
    return Color.fromRGBO(Random().nextInt(256), Random().nextInt(256), Random().nextInt(256), 1);
  }
}
